<?php

use \Yii, \CWidget;

/**
 * AHighcharts.
 * 
 * This file is the widget class of the aadam-highcharts project 
 * The widget implements functionality for the highcharts JS library that is the charting library 
 *
 * Please, put the valid parameters to use the widget (Please, check http://api.highcharts.com/highcharts for more info)
 *
 * @author Sysprog <sysprog@martis-ua.com>
 * @link http://www.aadam.com/,  https://code.google.com/p/aadam-highcharts/
 * @copyright Copyright &copy; 2013 
 * @license http://creativecommons.org/licenses/by-nc/3.0/
 * @version 1.0.0.1 $
 */
 
 class HighchartsTool extends \CWidget
 {
	/**
	 * @var string identificator of the chart
	 */
	public $id = "";
	
	/**
	 * @var string identificator of the charts container
	 */
	public $container = "";

    /**
     * @var array options regarding the chart area and plot area as well as general chart options
     *                    some more details: http://api.highcharts.com/highcharts#chart
     */
    public $chart = array("alignTicks" => true, 

			"animation" => true,
			"backgroundColor" => "#FFFFFF",
			"borderColor" => "#4572A7",
			"borderRadius" => 5,
			"borderWidth" => 0,
			"className" => null,  // CSS class name for chart container div, allows unique CSS for every chart
			"defaultSeriesType" => "line", // alias of type option

			"events" => array(  // http://api.highcharts.com/highcharts#chart.events
				"addSeries" => "function(event) { To function code } ",
				"click" => "function(event) { To function code } ",
				"load" => "function(event) { To function code } ",
				"redraw" => "function(event) { To function code } ",
				"selection" => "function(event) { To function code } ",
			),

			"height" => null,
			"ignoreHiddenSeries" => true,
			"inverted" => false,
			"margin" => null, //  The margin between the outer edge of the chart and the plot area. The numbers in the array designate top, right, bottom and left respectively.
			"marginBottom" => null,
			"marginLeft" => null,
			"marginRight" => null,
			"marginTop" => null,
			"pinchType" => null,
			"plotBackgroundColor" => null,
			"plotBackgroundImage" => null,
			"plotBorderColor" => "#C0C0C0",
			"plotBorderWidth" => 0,
			"plotShadow" => false,
			"polar" => false,
			"reflow" => true,
			"renderTo" => null, // selector of the HTML element where the chart will be rendered 
			"resetZoomButton" => array( // The button that appears after a selection zoom, allowing the user to reset zoom.
				"position" => null,
				"relativeTo" => "plot", // Can be either "plot" or "chart"
				"theme" => null
			),
			"selectionMarkerFill" => "rgba(69,114,167,0.25)",
			"shadow" => false,
			"showAxes" => false,
			"spacingBottom" => 15,
			"spacingLeft" => 10,
			"spacingRight" => 10,
			"spacingTop" => 10,
			"style" => null,
			"type" => "line", //  line, spline, area, areaspline, column, bar, pie, scatter, arearange, areasplinerange and columnrange 
			"width" => null,
			"zoomType" => null);


    public    $colors = array();  // An array containing the default colors for the chart's series. When all colors are used, new colors are pulled from the start again. Defaults to: 
								  //    array('#2f7ed8', '#0d233a', '#8bbc21', '#910000', '#1aadce', '#492970', '#f28f43', '#77a1e5', '#c42525', '#a6c96a'

    public  $credits = array(   // Highchart by default puts a credits label in the lower right corner of the chart. This can be changed using these options
								// http://api.highcharts.com/highcharts#credits
                "enabled" => true,
                "href" => "http://www.highcharts.com",
                "position" => null,
                "style" => null,
                "text" => "Highcharts.com"
        );

    public  $exporting = array(
			"chartOptions" => null,
			"enabled" => true,
			"filename" => "chart",
			"scale" => 2,
			"type" => "image/png",
			"url" => "http://export.highcharts.com",
			"width" => "undefined"
		);

    public  $labels = array(
					"items" => array( array("html" => 'Inner HTML or text for the label' , "style" => "{left: '100px', top: '100px'}" ) ), 
					"style" => null //Shared CSS styles for all labels. Defaults to: style => "{ color: '#3E576F' }"
					);

    public  $lang = array(
                "contextButtonTitle" => "Chart context menu",
                "decimalPoint" => ".",
                "downloadJPEG" => "Download JPEG image",
                "downloadPDF" => "Download PDF document",
                "downloadPNG" => "Download PNG image",
                "downloadSVG" => "Download SVG vector image",
                "loading" => "Loading...",
                "resetZoom" => "Reset zoom",
                "resetZoomTitle" => "Reset zoom level 1:1",
                "weekdays" => array() //array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
           );

    public  $legend = array(

            "align" => "center",
            "backgroundColor" => null,
            "borderColor" => "#909090",
            "borderRadius" => 5,
            "borderWidth" => 1,
            "enabled" => true,
            "floating" => false,
            "itemHiddenStyle" => null,
            "itemHoverStyle" => null,
            "itemMarginBottom" => 0,
            "itemMarginTop" => 0,
            "itemStyle" => null,
            "itemWidth" => null,
            "labelFormat" => "{name}",
            "labelFormatter" => null,
            "layout" => "horizontal",
            "lineHeight" => 16,
            "margin" => 15,
            "maxHeight" => null,
            "navigation" => array(
                    "activeColor" => "#3E576F",
                    "animation" => true,
                    "arrowSize" => 12,
                    "inactiveColor" => "#CCC",
                    "style" => null
            ),

            "padding" => 8,
            "reversed" => false,
            "rtl" => false,
            "shadow" => false,
            "style" => null,
            "symbolPadding" => 5,
            "symbolWidth" => 30,
            "title" => array(
                "style" => "",
                "text" => null
            ),
            "useHTML" => false,
            "verticalAlign" => "bottom",
            "width" => null,
            "x" => 0,
            "y" => 0
        );

    public  $loading = array(
            "hideDuration" => 100,
            "labelStyle" => null,
            "showDuration" => 100,
            "style" => null
        );

    public  $navigation = array(
            "buttonOptions" => array(), 
            "menuItemHoverStyle" => null,
            "menuItemStyle" => null,
            "menuStyle" => null
        );

    public  $pane = array(
                    "background" => null,
                    "center" => null,
                    "endAngle" => null,
                    "startAngle" => null);

    public  $plotOptions = array(
            "area" => array(),
            "arearange" => array(),
            "areaspline" => array(),
            "areasplinerange" => array(),
            "bar" => array(),
            "boxplot" => array(),
            "bubble" => array(),
            "column" => array(),
            "columnrange" => array(),
            "errorbar" => array(),
            "funnel" => array(),
            "gauge" => array(),
            "line" => array(),
            "pie" => array(),
            "scatter" => array(),
            "series" => array(),
            "spline" => array(),
            "waterfall" => array()
        );

    public  $series = array(
            "data" => array(),
            "dataParser" => null,
            "dataURL" => null,
            "index" => null,
            "legendIndex" => null,
            "name" => null,
            "stack" => null,
            "type" => null,
            "xAxis" => 0,
            "yAxis" => 0
        );

    public  $subtitle = array(
            "align" => "center",
            "floating" => false,
            "style" => null,
            "text" => null,
            "useHTML" => "false",
            "verticalAlign" => "top",
            "x" => 0,
            "y" => 30  );

    public  $title = array(
            "align" => "center",
            "floating" => false,
            "margin" => 15,
            "style" => null,
            "text" => "Chart title",
            "useHTML" => false,
            "verticalAlign" => "top",
            "x" => 0,
            "y" => 15);

    public  $tooltip = array(
                "animation" => true,
                "backgroundColor" => "rgba(255, 255, 255, 0.85)",
                "borderColor" => "auto",
                "borderRadius" => 3,
                "borderWidth" => 1,
                "crosshairs" => null,
                "enabled" => true,
                "followPointer" => false,
                "footerFormat" => false,
                "formatter" => null,
                "hideDelay" => 500,
                "pointFormat" => null,
                "positioner" => null,
                "shadow" => true,
                "shared" => false,
                "snap" => null,
                "style" => null,
                "useHTML" => false,
                "valueDecimals" => null,
                "valuePrefix" => null,
                "valueSuffix" => null,
                "xDateFormat" => null,
        );

    public  $xAxis = array(  // The X axis or category axis. Normally this is the horizontal axis, though if the chart is inverted this is the vertical axis. 
                           //  http://api.highcharts.com/highcharts#xAxis
            "allowDecimals" => true,
            "alternateGridColor" => null,
            "categories" => null,
            "dateTimeLabelFormats" => null,
            "endOnTick" => false,
            "events" => array(),
            "gridLineColor" => "#C0C0C0",
            "gridLineDashStyle" => "Solid",
            "gridLineWidth" => 0,
            "id" => null,
            "labels" => array(),
            "lineColor" => "#C0D0E0",
            "lineWidth" => 1,
            "linkedTo" => null,
            "max" => null,
            "maxPadding" => 0.01,
            "maxZoom" => null,
            "min" => null,
            "minPadding" => 0.01,
            "minRange" => null,
            "minTickInterval" => null,
            "minorGridLineColor" => "#E0E0E0",
            "minorGridLineDashStyle" => "Solid",
            "minorGridLineWidth" => 1,
            "minorTickColor" => "#A0A0A0",
            "minorTickInterval" => null,
            "minorTickLength" => 2,
            "minorTickPosition" => "outside",
            "minorTickWidth" => 0,
            "offset" => 0,
            "opposite" => false,
            "plotBands" => array(),
            "plotLines" => array(),
            "reversed" => false,
            "showEmpty" => true,
            "showFirstLabel" => true,
            "showLastLabel" => false,
            "startOfWeek" => 1,
            "startOnTick" => false,
            "tickColor" => "#C0D0E0",
            "tickInterval" => null,
            "tickLength" => 5,
            "tickPixelInterval" => null,
            "tickPosition" => "outside",
            "tickPositioner" => null,
            "tickPositions" => null,
            "tickWidth" => 1,
            "tickmarkPlacement" => "between",
            "title" => array(),
            "type" => "linear"
        );

    public    $yAxis = array( // the same as yAxis

        ) ;
		
	/**
	 * @var string how to show the overflow of the tree content 
	 */
	public $overflow = 'auto';
	
	public $multi = false;

	public $initClientScript = true;

	public $options = array();
	
	private function getProperty($property, $type = 'array')
	{
		$result = $property;
		if(is_array($property))
		{
			$result = array();
			foreach($property as $ppt => $value)
			{
				$result[$ppt] = $this->getProperty($value);
			}
		}

		return $result;
	}
	
	private function replaceBraskets($json)
	{
		return preg_replace("/[{|\[]/", "[{", preg_replace("/[}|\]]/", "}]", $json));
	}

	public function init()
	{
		$id = $this->getId();
		if($id == '')
		{
			$id = rand(5, 10);
		}
		
		if($this->container == '')
		{
			$this->container = "container_".$id;
		}

		$options = $this->getOptions();
		$options['id'] = $id;
		$options['container'] = $this->container;
		
		$options['chart']['renderTo'] = $this->container;

		$cs = Yii::app()->getClientScript();
		
		if($this->initClientScript)
		{
			$jsUrl = "http://code.highcharts.com/highcharts.js";
			$cs->registerScriptFile($jsUrl);

			$jsUrl = "http://code.highcharts.com/modules/exporting.js";
			$cs->registerScriptFile($jsUrl);
		}

		$script = "  $(document).ready(function() { var chart = new Highcharts.Chart( {
		
			chart: ".json_encode($options['chart'])." ,
			title: ".json_encode($options['title'])." ,
			
            xAxis: ".json_encode($options['xAxis'])." ,
			yAxis: ".$this->replaceBraskets(json_encode($options['yAxis']))." ,

			legend: ".json_encode($options['legend'])." ,
			tooltip: ".json_encode($options['tooltip'])." ,

			subtitle: ".json_encode($options['subtitle'])." ,
			series: ".json_encode($options['series'])." ,

			credits: ".json_encode($options['credits'])." ,
			exporting: ".json_encode($options['exporting'])." ,
			
			legend: ".json_encode($options['legend'])." ,
			loading: ".json_encode($options['loading'])." ,
			navigation: ".json_encode($options['navigation'])." ,
			
			pane: ".json_encode($options['pane'])." ,

			}); }); ";

		$cs->registerScript("Highchart#".$id, $script);
	}

	public function getOptions()
	{
		$options = $this->options;

		foreach(array('chart', 'colors', 'credits', 'exporting', 'labels', 'lang', 'legend', 'loading', 'navigation', 'pane', 'plotOptions', 'series', 'subtitle', 'title', 'tooltip', 'xAxis', 'yAxis') as $name)
		{
			if($this->$name != null)
			{
				$options[$name] = $this->getProperty($this->$name);
			}
			else
			{
				$options[$name] = null;
			}
		}

		return $options;
	}

	public function run()
	{

	}
 }
 
?>